
#pragma once
 
#include <list>
 
/*
*   基于乐观锁的链表
*/
template <typename T>
class LockfreeList
{
    private: 
        std::list<T> list;
        
    private:
        int mutex;
        int lock;
        int unlock;
    public:
        LockfreeList():
        mutex(0),
        lock(0),
        unlock(1)
        {

        };
        
        ~LockfreeList(){};
        void Lock()
        {
            while( !__sync_bool_compare_and_swap (&mutex,lock, 1) )
            {
                usleep(100);
            }
        }
        void Unlock()
        {
            __sync_bool_compare_and_swap (&mutex,unlock, 0) ;
        }
        void Push(T data)
        {
            Lock();
            list.push_back(data);
            Unlock();
        }
        T Front()
        {
            Lock();
            T data = list.front();
            Unlock();
            return data;
        }
        void PopFront()
        {
            Lock();
            list.pop_front();
            Unlock();
        }
        bool IsEmpty()
        {
            Lock();
            if( list.empty() )
            {
                Unlock();
                return true;
            }
            else
            {
                Unlock();
                return false;
            }
        }

        bool Find(T data)
        {
            typename std::list<T>::iterator it;
            Lock();
            for ( it = list.begin(); it != list.end(); ++it)
            {
                if( *it == data )
                {
                    Unlock();
                    return true;
                }
            }
            Unlock();
            return false;
        }
};
 
